public class Product {
    /*
    题目: 乘积最大子数组
    https://leetcode.cn/problems/maximum-product-subarray/
     */
    public int maxProduct(int[] nums) {
        int n = nums.length;
        int maxn = 1;
        int minn = 1;

        int src = Integer.MIN_VALUE;
        for (int i = 0; i < n; i ++) {
            if (nums[i] < 0) {
                int t = maxn;
                maxn = minn;
                minn = t;
            }

            maxn = Math.max(maxn * nums[i], nums[i]);
            minn = Math.min(minn * nums[i], nums[i]);
            src = Math.max(src, maxn);
        }

        return src;
    }
    /*
    题目: 乘积为正数的最长子数组长度
    https://leetcode.cn/problems/maximum-length-of-subarray-with-positive-product/
     */
    public int getMaxLen(int[] nums) {
        int n = nums.length;
        // 乘积为正数的最长子数组
        int[] positive = new int[n];
        // 成绩为负数的最长子数组
        int[] negative = new int[n];
        positive[0] = nums[0] > 0 ? 1 : 0;
        negative[0] = nums[0] < 0 ? 1 : 0;

        int src = positive[0];
        for (int i = 1; i < n; i ++) {
            if (nums[i] > 0) {
                // 乘积正 直接加
                positive[i] = positive[i - 1] + 1;
                // 上一个乘积为负 且长度不为 0 , 就 + 1
                negative[i] = negative[i - 1] > 0 ? negative[i - 1] + 1 : 0;
            } else if (nums[i] < 0) {
                // 正数长度取决于 上一个负数长度 (必须要存在负数)
                positive[i] = negative[i - 1] > 0 ? negative[i - 1] + 1 : 0;
                // 负数长度也 取决于 上一个正数长度 (可以不存在正数)
                negative[i] = positive[i - 1] + 1;
            } else {
                negative[i] = positive[i] = 0;
            }

            src = Math.max(src, positive[i]);
        }

        return src;
    }
}
